<template>
  <div class="user-list">
    <a-card title="用户列表">
      <template #extra>
        <a-button type="primary" @click="handleAdd">新增用户</a-button>
      </template>

      <a-form layout="inline" class="search-form">
        <a-form-item label="用户名">
          <a-input v-model:value="searchForm.search" placeholder="请输入用户名" allow-clear style="width: 200px" />
        </a-form-item>
        <a-form-item label="班级">
          <a-input v-model:value="searchForm.class_name" placeholder="请输入班级" allow-clear style="width: 200px" />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="handleSearch">查询</a-button>
          <a-button style="margin-left: 8px" @click="handleReset">重置</a-button>
        </a-form-item>
      </a-form>

      <a-table 
        :columns="columns" 
        :data-source="dataSource" 
        :loading="loading"
        bordered 
        :pagination="pagination"
        :scroll="{ x: 1200 }"
      >
        <template #bodyCell="{ column, record }">
          <!-- 四级成绩 -->
          <template v-if="column.key === 'cet4'">
            <div v-if="record.profile">
              <div>
                成绩：{{ record.profile.cet4_score || '-' }}
              </div>
              <a-tag :color="getCETStatusColor(record.profile.cet4_status)" size="small">
                {{ record.profile.cet4_status || '未提交' }}
              </a-tag>
            </div>
            <span v-else>-</span>
          </template>
          
          <!-- 六级成绩 -->
          <template v-if="column.key === 'cet6'">
            <div v-if="record.profile">
              <div>
                成绩：{{ record.profile.cet6_score || '-' }}
              </div>
              <a-tag :color="getCETStatusColor(record.profile.cet6_status)" size="small">
                {{ record.profile.cet6_status || '未提交' }}
              </a-tag>
            </div>
            <span v-else>-</span>
          </template>
          
          <!-- 操作列 -->
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="handleView(record)">查看</a>
              <a @click="handleEdit(record)">编辑</a>
              <a 
                v-if="record.profile?.cet4_status === '审核中'" 
                @click="showReviewModal(record, 'cet4')"
                style="color: #1890ff"
              >
                四级审核
              </a>
              <a 
                v-if="record.profile?.cet6_status === '审核中'" 
                @click="showReviewModal(record, 'cet6')"
                style="color: #1890ff"
              >
                六级审核
              </a>
              <a style="color: #ff4d4f" @click="handleDelete(record)">删除</a>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
    
    <!-- 审核弹窗 -->
    <a-modal
      v-model:open="reviewModalVisible"
      :title="reviewModalTitle"
      @ok="handleReview"
      :confirmLoading="reviewing"
      width="700px"
    >
      <a-descriptions bordered :column="1" size="small">
        <a-descriptions-item label="学生">
          {{ currentReviewUser?.username }}
        </a-descriptions-item>
        <a-descriptions-item label="学号">
          {{ currentReviewUser?.profile?.student_id || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="成绩">
          {{ currentCETScore }}
        </a-descriptions-item>
      </a-descriptions>
      
      <!-- 证明图片 -->
      <a-divider orientation="left">证明材料</a-divider>
      <a-row :gutter="16">
        <a-col :span="12">
          <div style="text-align: center">
            <div style="margin-bottom: 8px; font-weight: 500">免修证明图片</div>
            <a-image
              :src="currentExemptionPic"
              :fallback="''"
              style="max-width: 100%; border: 1px solid #d9d9d9; border-radius: 4px"
            />
          </div>
        </a-col>
        <a-col :span="12">
          <div style="text-align: center">
            <div style="margin-bottom: 8px; font-weight: 500">成绩证明图片</div>
            <a-image
              :src="currentScorePic"
              :fallback="''"
              style="max-width: 100%; border: 1px solid #d9d9d9; border-radius: 4px"
            />
          </div>
        </a-col>
      </a-row>
      
      <a-divider />
      
      <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="审核操作" required>
          <a-radio-group v-model:value="reviewForm.action">
            <a-radio value="approve">通过</a-radio>
            <a-radio value="reject">拒绝</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item 
          label="拒绝原因" 
          v-if="reviewForm.action === 'reject'"
          required
        >
          <a-textarea 
            v-model:value="reviewForm.reason" 
            :rows="3" 
            placeholder="请输入拒绝原因"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message, Modal } from 'ant-design-vue'
import { userAPI } from '@/api/user'
import type { UserDetail } from '@/api/user'

const router = useRouter()
const loading = ref(false)
const dataSource = ref<UserDetail[]>([])

// 审核相关
const reviewModalVisible = ref(false)
const reviewModalTitle = ref('')
const reviewing = ref(false)
const currentReviewUser = ref<UserDetail | null>(null)
const currentCETType = ref<'cet4' | 'cet6'>('cet4')

const reviewForm = reactive({
  action: 'approve' as 'approve' | 'reject',
  reason: ''
})

// 当前审核成绩
const currentCETScore = computed(() => {
  if (!currentReviewUser.value?.profile) return '-'
  return currentCETType.value === 'cet4' 
    ? currentReviewUser.value.profile.cet4_score || '-'
    : currentReviewUser.value.profile.cet6_score || '-'
})

// 当前免修证明图片
const currentExemptionPic = computed(() => {
  if (!currentReviewUser.value?.profile) return ''
  return currentCETType.value === 'cet4'
    ? currentReviewUser.value.profile.cet4_exemption_pic || ''
    : currentReviewUser.value.profile.cet6_exemption_pic || ''
})

// 当前成绩证明图片
const currentScorePic = computed(() => {
  if (!currentReviewUser.value?.profile) return ''
  return currentCETType.value === 'cet4'
    ? currentReviewUser.value.profile.cet4_score_pic || ''
    : currentReviewUser.value.profile.cet6_score_pic || ''
})

// 搜索表单
const searchForm = reactive({
  search: '',
  class_name: ''
})

const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
  { title: '用户名', dataIndex: 'username', key: 'username', width: 120 },
  { title: '学号', dataIndex: ['profile', 'student_id'], key: 'student_id', width: 120 },
  { title: '班级', dataIndex: ['profile', 'class_name'], key: 'class_name', width: 100 },
  { title: '四级成绩', key: 'cet4', width: 150 },
  { title: '六级成绩', key: 'cet6', width: 150 },
  { title: '操作', key: 'action', width: 250, fixed: 'right' }
]

const pagination = ref({
  total: 0,
  current: 1,
  pageSize: 10,
  showSizeChanger: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.value.current = page
    pagination.value.pageSize = pageSize
    loadData()
  }
})

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const res = await userAPI.getUserList({
      page: pagination.value.current,
      page_size: pagination.value.pageSize,
      search: searchForm.search || undefined,
      class_name: searchForm.class_name || undefined
    })
    dataSource.value = res.data.results
    pagination.value.total = res.data.count
  } catch (error: any) {
    message.error('加载数据失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.value.current = 1
  loadData()
}

// 重置
const handleReset = () => {
  searchForm.search = ''
  searchForm.class_name = ''
  pagination.value.current = 1
  loadData()
}

// 新增用户
const handleAdd = () => {
  // TODO: 打开新增对话框
  message.info('功能开发中...')
}

// 查看详情
const handleView = (row: UserDetail) => {
  router.push(`/users/profile/${row.id}`)
}

// 编辑用户
const handleEdit = (row: UserDetail) => {
  router.push(`/users/edit/${row.id}`)
}

// 删除用户
const handleDelete = (row: UserDetail) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除用户「${row.username}」吗？`,
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      try {
        await userAPI.deleteUser(row.id)
        message.success('删除成功')
        loadData()
      } catch (error: any) {
        message.error('删除失败: ' + (error.response?.data?.message || error.message))
      }
    }
  })
}

// 四六级状态颜色
const getCETStatusColor = (status?: string) => {
  const colorMap: Record<string, string> = {
    '未提交': 'default',
    '审核中': 'processing',
    '已通过': 'success',
    '未通过': 'error'
  }
  return colorMap[status || '未提交'] || 'default'
}

// 显示审核弹窗
const showReviewModal = (user: UserDetail, type: 'cet4' | 'cet6') => {
  currentReviewUser.value = user
  currentCETType.value = type
  reviewModalTitle.value = type === 'cet4' ? '英语四级成绩审核' : '英语六级成绩审核'
  reviewForm.action = 'approve'
  reviewForm.reason = ''
  reviewModalVisible.value = true
}

// 执行审核
const handleReview = async () => {
  if (reviewForm.action === 'reject' && !reviewForm.reason) {
    message.error('请填写拒绝原因')
    return
  }
  
  if (!currentReviewUser.value) return
  
  reviewing.value = true
  try {
    const res = await userAPI.reviewCET(currentReviewUser.value.id, {
      exam_type: currentCETType.value,
      action: reviewForm.action,
      reason: reviewForm.reason
    })
    
    message.success(res.data.message || '审核成功')
    reviewModalVisible.value = false
    
    // 重新加载数据
    await loadData()
  } catch (error: any) {
    message.error('审核失败: ' + (error.response?.data?.message || error.message))
  } finally {
    reviewing.value = false
  }
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.search-form {
  margin-bottom: 20px;
}
</style>
